package components
{
	import flash.events.MouseEvent;
	
	import mx.managers.DragManager;
	
	import spark.components.Group;
	import spark.components.Panel;
	
	/**
	 * A simple extension of the Spark Panel component
	 * that enables dragging.
	 */
	public class DraggablePanel extends Panel
	{
		//--------------------------------------
		// Constructor
		//--------------------------------------
		
		public function DraggablePanel()
		{
			super();
		}
		
		//--------------------------------------
		// Skin Parts
		//--------------------------------------
		
		/**
		 * The skin part that represents the title bar of the underlying Panel.
		 *	NOTE: The default PanelSkin already has this, it's just not defined as a skinPart in the Panel class.
		 * We want it so that we can capture dragging.
		 */
		[SkinPart(required="true")]
		public var topGroup:Group;
		
		//--------------------------------------
		// Overridden Methods
		//--------------------------------------
		
		protected override function partAdded( partName:String, instance:Object ) : void
		{
			super.partAdded( partName, instance );
			
			if (instance == topGroup)
			{
				Group( instance ).addEventListener( MouseEvent.MOUSE_DOWN, topGroup_mouseDownHandler );
				Group( instance ).addEventListener( MouseEvent.MOUSE_UP, topGroup_mouseUpHandler );
			}
		}
		
		protected override function partRemoved( partName:String, instance:Object ) : void
		{
			super.partRemoved( partName, instance );
			
			if (instance == topGroup)
			{
				Group( instance ).removeEventListener( MouseEvent.MOUSE_DOWN, topGroup_mouseDownHandler );
				Group( instance ).removeEventListener( MouseEvent.MOUSE_UP, topGroup_mouseUpHandler );
			}
		}
		
		//--------------------------------------
		// Event Handlers
		//--------------------------------------
		
		protected function topGroup_mouseDownHandler( event:MouseEvent ):void
		{
			if ( !DragManager.isDragging )
				startDrag();
		}
		
		protected function topGroup_mouseUpHandler( event:MouseEvent ):void
		{
			stopDrag();
		}
	}
}